#include <Arduino.h>
// 定义使用的引脚和PWM通道
#define LED_CHANNEL 0
#define LED_PIN 8

#include "index.h"
#include "main.h"
#include <WiFiManager.h>


// Web服务器实例
WebServer server(80);

String sendHTML();

void saveConfigCallback() {
  server.send(200, "text/html", WiFi.localIP().toString());
}

void handleLED() {
  String ledState = "OFF";
  String LED_State = server.arg("LEDstate");
  int pin = server.arg("LEDstate").toInt();
  out(pin);
  if (LED_State == "1") {
    digitalWrite(LED_PIN, LOW); // LED 点亮
    ledState = "ON";            // 反馈参数
  } else {
    digitalWrite(LED_PIN, HIGH); // LED 熄灭
    ledState = "OFF";            // 反馈参数
  }

  server.send(200, "text/plain", ledState); // 发送网页
}

void handleADC() {
  int a = analogRead(A0);
  String adcValue = String(a);

  server.send(200, "text/plain", adcValue); // 发送模拟输入引脚到客户端ajax请求
}
void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);

  WiFiManager wm;
  bool res;
  // res = wm.autoConnect(); // auto generated AP name from chipid
  res = wm.autoConnect("esp32-c3"); // anonymous ap
  // res = wm.autoConnect("AutoConnectAP","password"); // password protected ap

  if (!res) {
    Serial.println("Failed to connect");
    // ESP.restart();
  } else {
    // if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
  }
  Serial.print("Connected to WiFi : ");
  Serial.println(WiFi.SSID());
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  blink(LED_PIN, 500, 3);
  wm.setSaveConfigCallback(saveConfigCallback);

  // 设置路由处理程序
  server.on("/", HTTP_GET, []() { server.send(200, "text/html", indexx); });
  server.on("/setLED", handleLED);
  server.on("/readADC", handleADC);
  server.begin();
  high(LED_PIN);
  Serial.println("HTTP server started");
}

void loop() { server.handleClient(); }

// ESP32-C3FN4 – 停产
// PLATFORM: Espressif 32 (6.9.0) > Espressif ESP32-C3-DevKitM-1
// HARDWARE: ESP32C3 160MHz, 320KB RAM, 4MB Flash
// Chip is ESP32-C3 (revision v0.4)
// Features: WiFi, BLE
// Crystal is 40MHz
// MAC: 10:00:3b:01:42:84